package com.hy.common.config.thread;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author: 王富贵
 * @description: 线程池基本配置参数
 * @createTime: 2022年04月21日 20:59:15
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Value("${async.executor.thread.core_pool_size}")
    private int corePoolSize;

    @Value("${async.executor.thread.max_pool_size}")
    private int maxPoolSize;

    @Value("${async.executor.thread.keep_alive_seconds}")
    private int keepAliveSeconds;

    @Value("${async.executor.thread.name.prefix}")
    private String namePrefix;

    /**
     * 更新数据库或发送MQ消息线程池。io密集型，开大线程池
     * @return 线程池
     */
    @Bean("UpdateAndSendExecutor")
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //设置队列大小
        executor.setQueueCapacity(Integer.MAX_VALUE);
        //设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //设置默认线程名称
        executor.setThreadNamePrefix("baseExecutor");
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);
        //秩序初始化
        executor.initialize();
        return executor;
    }
}
